package com.lsyw.intergrate.controller;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lsyw.intergrate.entity.MesDevice;
import com.lsyw.intergrate.entity.MesPoint;
import com.lsyw.intergrate.service.MesDeviceService;
import com.lsyw.intergrate.service.MesPointService;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.lsyw.intergrate.entity.common.PageInfo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lsyw.intergrate.common.Result;
import org.springframework.util.CollectionUtils;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import com.lsyw.intergrate.service.MesPointDataService;
import com.lsyw.intergrate.entity.MesPointData;

import java.util.*;

import io.swagger.annotations.Api;
import lombok.Data;

import org.springframework.stereotype.Controller;
import org.springframework.web.client.RestTemplate;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 刘磊
 * @since 2024-02-21
 */
@Api(tags = "mes监控点采集数据")
@RestController
@RequestMapping("/mes-point-data")
public class MesPointDataController {


    @Autowired
    private MesPointDataService mesPointDataService;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private MesDeviceService mesDeviceService;
    @Autowired
    private MesPointService mesPointService;

    /**
     * 通过id查询
     */
    @PostMapping("/test")
    public Result test() {
        final LambdaQueryWrapper<MesDevice> lambda = new QueryWrapper<MesDevice>().lambda();
        lambda.eq(MesDevice::getDelFlag, 0);
        List<MesDevice> list = mesDeviceService.list(lambda);
        list.forEach(e -> {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

            MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
            formData.add("GRM", "54656790108");
            formData.add("PASS", "2024ddbs");
            formData.add("XINFO", "1");

            HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(formData, headers);

            String url = "http://www.yunplc.com:7080/exlog";
            // 假设服务器返回String表示操作结果
            String response = restTemplate.postForObject(url, requestEntity, String.class);
            if ((!response.contains("ERROR")) && response.contains("OK")) {
                String[] array = response.split("\r\n");
                String sid = array[2] + "&OP=R";
                String ip = array[1].substring(5);
                System.out.println(sid);
                final LambdaQueryWrapper<MesPoint> lambdaPoint = new QueryWrapper<MesPoint>().lambda();
                lambdaPoint.eq(MesPoint::getDelFlag, 0);

                List<MesPoint> pointList = mesPointService.list(lambdaPoint);
                final String[] param = {pointList.size() + "\r\n"};
                pointList.forEach(k -> {
                    param[0] += k.getName() + "\r\n";
                });
                param[0] = param[0].substring(0, param[0].length() - 2);
                System.out.println(param[0]);
                String url2 = "http://" + ip + "/exdata?" + sid;


                Date date =new Date();
                Long cn = date.getTime();
                String request = HttpRequest.post(url2)
                        .header("Content-Type", "application/text")
                        .body(param[0])
                        .execute().body();
                System.out.println(request);
                if ((!request.contains("ERROR")) && request.contains("OK")) {
                    String[] array2 = request.split("\r\n");
                    if (array2[0].equals("OK")) {
                        for (int i = 0; i < pointList.size(); i++) {
                            MesPointData mesPointData = new MesPointData();
                            mesPointData.setPointName(pointList.get(i).getName());
                            mesPointData.setMassifId(e.getMassifId());
                            mesPointData.setDeviceId(e.getId());
                            mesPointData.setCn(cn);
                            if (!array2[i + 2].contains("#")) {
                                mesPointData.setValue(Double.valueOf(array2[i + 2]));
                            }else{
                                mesPointData.setValue(0.0);
                            }
                            mesPointData.setDate(date);
                            mesPointData.setDelFlag(0);
                            mesPointDataService.save(mesPointData);
                        }
                    } else {
                        e.setStatus(2);
                        mesDeviceService.updateById(e);
                    }
                } else {
                    e.setStatus(2);
                    mesDeviceService.updateById(e);
                }

            } else {
                e.setStatus(2);
                mesDeviceService.updateById(e);
            }
        });


        // 处理响应
        return Result.successResult(null);
    }

    /**
     * 查询列表
     */
    @PostMapping("/list")
    public Result list(@RequestBody MesPointDataReqVo mesPointData) {
        final LambdaQueryWrapper<MesPointData> lambda = new QueryWrapper<MesPointData>().lambda();
        this.buildCondition(lambda, mesPointData);
        return Result.successResult(mesPointDataService.list(lambda));
    }

    /**
     * 分页查询
     */
    @PostMapping("/page")
    public Result page(@RequestBody PageInfo pageInfo) {
        Page<MesPointData> page = new Page<>();
        page.setSize(pageInfo.getPageSize());
        page.setCurrent(pageInfo.getPageNum());
        final LambdaQueryWrapper<MesPointData> lambda = new QueryWrapper<MesPointData>().lambda();
        //TODO 自己的查询逻辑
        return Result.successResult(this.mesPointDataService.page(page, lambda));
    }


    /**
     * 构造查询条件
     *
     * @param lambda
     * @param param
     */
    private void buildCondition(LambdaQueryWrapper<MesPointData> lambda, MesPointDataReqVo param) {
        if (!StringUtils.isEmpty(param.getId())) {
            lambda.eq(MesPointData::getId, param.getId());
        }
        if (!StringUtils.isEmpty(param.getPointName())) {
            lambda.eq(MesPointData::getPointName, param.getPointName());
        }
        if (!StringUtils.isEmpty(param.getValue())) {
            lambda.eq(MesPointData::getValue, param.getValue());
        }
        if (!CollectionUtils.isEmpty(param.getDateList())) {
            lambda.ge(MesPointData::getDate, param.getDateList().get(0));
            lambda.le(MesPointData::getDate, param.getDateList().get(1));
        }
        if (!StringUtils.isEmpty(param.getDelFlag())) {
            lambda.eq(MesPointData::getDelFlag, param.getDelFlag());
        }
        if (!StringUtils.isEmpty(param.getMassifId())) {
            lambda.eq(MesPointData::getMassifId, param.getMassifId());
        }
        lambda.orderBy(true, false, MesPointData::getId);
    }


    /**
     * 请求model
     */
    @Data
    @AllArgsConstructor
    private static class MesPointDataReqVo extends MesPointData {
        private List<String> dateList; // 采集时间起止
    }


}
